/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 牛孟俊
 * Date: 2023-11-09
 * Time: 16:34
 */
public class HashBucket {

    static class Node{
        private int key;
        private int value = 888;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;

        }
    }

    public Node[] array;
    public int usedSize;
    //默认的负载因子为0.75
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;


    public HashBucket() {
        this.array = new Node[10];
    }

    public void put(int key, int value) {
        Node node = new Node(key,value);
        int index = key % array.length;
        //遍历一下index位置的链表
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                //有一样的key则更新value
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        //cur等于null,没有这个key，进行尾插或者头插   这里进行的是头插
        node.next = array[index];
        array[index] = node;

        usedSize++;
        //计算负载因子
        if(loadFactor() >= 0.75) {
            //进行扩容
            resize();
        }

    }

    //重新哈希原来的数据，进行扩容
    private void resize() {
        //二倍扩容
        Node[] tmpArray = new Node[array.length*2];
        //变量原来的数组下标的每个链表
        for(int i = 0; i < array.length; i++) {
            Node cur = array[i];
                while(cur != null) {
                    Node curNext = cur.next;//需要记录下来原来链表的下个节点的位置
                    int index = cur.key % tmpArray.length;//新数组的位置
                    //采用头插放到新数组index位置
                    cur.next = tmpArray[index];//这里修改之后cur的next已经发生变化了
                    tmpArray[index] = cur;
                    cur = curNext;
                }
        }
        array = tmpArray;
    }


    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }

    /**
     * 通过key值返回一个value
     * @param key
     * @return
     */
    public int get(int key) {
        //key所对应数组当中的位置
        int index = key % array.length;
        Node cur = array[index];
        //遍历链表，找到key所对应的value
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
        }
        return -1;
    }

}
